package com.gxa.meiye.admin.shop.interceptor;

import com.gxa.meiye.core.exception.BusinessException;
import com.gxa.meiye.core.exception.ExceptionCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @Author cc
 * @PackageName meiye
 * @Package com.gxa.meiye.admin.shop.interceptor
 * @Date 2022/7/22 16:52
 * @Version 1.0
 */
@Component
public class TokenInterceptors implements HandlerInterceptor {

    @Autowired
    private RestTemplate restTemplate = null;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 从前端的请求头中获取token
        String token = request.getHeader("token");

        // 判断token 如果为null, 直接拦死
        if(StringUtils.isEmpty(token)){
            throw new BusinessException(ExceptionCode.EMPTY_TOKEN);
        }

        // 发起向Portal服务器的远程调用
        // url
        String url = "http://1.117.60.194:8081/shop/checkWithToken";

        // 请求头(包括请求类型)
        HttpHeaders httpHeaders = new HttpHeaders();
        // 指定了参数类型,对应java中的 @RequestParam
        // MediaType.APPLICATION_JSON 对应java中的 @RequestBody
        httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        // 如果要传递自定义的请求头
        // httpHeaders.set("token","");

        // 请求参数
        MultiValueMap<String,String> params =new LinkedMultiValueMap<>();
        params.add("token",token);

        // 请求类型
        // HttpEntity: Spring提供的一个传递http请求的实体类型
        HttpEntity httpEntity = new HttpEntity(params,httpHeaders);

        // 通过post方式发送请求的方法
        Map map = restTemplate.postForObject(url, httpEntity, Map.class);
        // code / data

        // 完成通信,获取SSO服务器返回的消息:
        // 正常数据: {"code"=1,"data"={id=5, name=user13568981610, phone=13568981610, lastLoginTime=2022-07-07 10:09:52}}
        //异常情况: {"code"=50008,"msg"="token校验不通过"}
        System.out.println("token验证的code"+map.get("code"));
        if(!map.get("code").equals("200")){
            throw new BusinessException(ExceptionCode.WRONG_TOKEN);
        }else {
            return true;
        }

    }
}
